package com.ruoyi.merchant.service.impl;

import com.ruoyi.common.core.cg.pojo.*;
import com.ruoyi.merchant.mapper.CommunityMapper;
import com.ruoyi.merchant.mapper.GroupMapper;
import com.ruoyi.merchant.mapper.LeaderMapper;
import com.ruoyi.merchant.service.GroupService;
import com.ruoyi.merchant.utils.QiniuUtils;
import com.ruoyi.merchant.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.UUID;

/**
* @author ？？？
* @description 针对表【group】的数据库操作Service实现
* @createDate 2025-03-14 15:37:02
*/
@Service
@Slf4j
public class GroupServiceImpl
    implements GroupService{

    @Autowired
    private GroupMapper groupMapper;
    @Autowired
    private LeaderMapper leaderMapper;
    @Autowired
    private CommunityMapper communityMapper;

    /**
     * 根据id查询商品信息表
     * @param lid
     * @return
     */
    @Override
    public List<Group> queryGroup(int lid) {
        List<Group> groupList = groupMapper.queryGroup(lid);
        return groupList;
    }

    @Override
    public Result groupList() {
        List<Group> groups = groupMapper.groupList();
        return Result.ok(groups);
    }

    /**
     * 发起拼团功能
     * @param group
     * @return
     */
    @Override
    @Transactional
    public Result saveGroup(Group group, MultipartFile surfacePlotFile, MultipartFile firstImgFile, MultipartFile secondImgFile) {
        try {
            // 上传封面图
            if (surfacePlotFile != null && !surfacePlotFile.isEmpty()) {
                String surfacePlotUrl = uploadToQiniu(surfacePlotFile);
                group.setSurfacePlot(surfacePlotUrl);
            }

            // 上传第一张配图
            if (firstImgFile != null && !firstImgFile.isEmpty()) {
                String firstImgUrl = uploadToQiniu(firstImgFile);
                group.setFirstImg(firstImgUrl);
            }

            // 上传第二张配图
            if (secondImgFile != null && !secondImgFile.isEmpty()) {
                String secondImgUrl = uploadToQiniu(secondImgFile);
                group.setSecondImg(secondImgUrl);
            }

            // 保存团信息到数据库
            group.setStatus(5);
            int saveGroup = groupMapper.saveGroup(group);
            Integer groupId = group.getId();
            LeaderGroup leaderGroup = new LeaderGroup();
            leaderGroup.setGroupId(groupId);
            leaderGroup.setLeaderId(group.getLeaderId());

            log.info("group：" + groupId + " leader：" + group.getLeaderId());
            leaderMapper.leaderGroupSave(leaderGroup);

            Community community = communityMapper.selectComByLid(group.getLeaderId());
            Integer communityId = community.getId();
            TCommunityGroup tCommunityGroup = new TCommunityGroup();
            tCommunityGroup.setGroupId(groupId);
            tCommunityGroup.setCommunityId(communityId);
            groupMapper.saveComGroup(tCommunityGroup);

            //添加t_store_group
            TLeaderStore leaderStore = groupMapper.selectStoreId(group.getLeaderId());
            Integer storeId = leaderStore.getStoreId();

            StoreGroup storeGroup = new StoreGroup();
            storeGroup.setGroupId(groupId);
            storeGroup.setStoreId(storeId);
            groupMapper.saveStoreGroup(storeGroup);


            return Result.ok(saveGroup);
        } catch (Exception e) {
            log.error("保存团信息失败", e);
            return Result.error("保存团信息失败");
        }
    }

    private String uploadToQiniu(MultipartFile file) throws Exception {
        if (file == null || file.isEmpty()) {
            log.error("上传文件为空: " + file);
            throw new IllegalArgumentException("上传的文件不能为空");
        }

        log.info("开始上传文件: " + file.getOriginalFilename());

        byte[] fileBytes = file.getBytes();
        String fileName = UUID.randomUUID().toString().replaceAll("-","");
        String oname = file.getOriginalFilename();
        String suffix = oname.substring(oname.lastIndexOf("."));
        fileName += suffix;
        String fileKey = QiniuUtils.upload2Qiniu(fileBytes, fileName);

        // 去除文件 URL 的协议部分（http:// 或 https://）
        if (fileKey.startsWith("http://") || fileKey.startsWith("https://")) {
            fileKey = fileKey.substring(fileKey.indexOf("/", fileKey.indexOf("://") + 3));
        }

        String fileUrl = "http://stcn3inqu.hb-bkt.clouddn.com/" + fileKey;
        log.info("上传文件成功, URL: " + fileUrl);

        return fileUrl;
    }
}




